#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: liang kang
@contact: gangkanli1219@gmail.com
@time: 2018/3/9 21:53
@desc: 
"""
import base64

import cv2
import numpy as np
from skimage import transform


def image_encode_base64(image):
    """
    图像转换为base64编码,然后转换为字符串

    Parameters
    ----------
    image

    Returns
    -------

    """
    code = cv2.imencode('.jpg', image)[1]
    code = base64.b64encode(code)
    code = base64.encodebytes(code)
    code = bytes.decode(code)
    return code


def image_decode_base64(string):
    """
    将字符串转化为图像

    Parameters
    ----------
    string

    Returns
    -------

    """
    byte = str.encode(string)
    byte = base64.decodebytes(byte)
    byte = base64.b64decode(byte)
    byte = np.frombuffer(byte, np.uint8)
    img = cv2.imdecode(byte, cv2.CAP_MODE_RGB)
    return img


def rotate_image(angle, image):
    """
    逆时针旋转一个图像 angle 度

    Parameters
    ----------
    angle: 要旋转的角度
    image: 原始图像

    Returns
    -------
    img_buf: 从旋转后的图像的中心切割出来与原始图像相同shape的图像
    offset: img_buf 相对于旋转后的图像的顶点（左上角）的起始坐标

    """
    shape = image.shape
    arc = angle * np.pi / 180
    post_size = (np.ceil(abs(shape[0] * np.cos(arc)) +
                         abs(shape[1] * np.sin(arc))).astype(np.int32),
                 np.ceil(abs(shape[0] * np.sin(arc)) +
                         abs(shape[1] * np.cos(arc))).astype(np.int32))
    offset = list(map(lambda x, y: (x - y) // 2, post_size, shape))
    if 0 == angle:
        img_buf = image.copy()
        img_buf = img_buf.astype(np.float32)
    else:
        img_buf = transform.rotate(image, angle,
                                   resize=True, preserve_range=True)
        img_buf = img_buf[offset[0]:(offset[0] + shape[0]),
                          offset[1]:(offset[1] + shape[1]), :]
    return offset, img_buf
